package sz.com.postoffice.jxyzwgcase.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import sz.com.postoffice.jxyzwgcase.dao.BaseDao;
import sz.com.postoffice.jxyzwgcase.dao.master.PersonnelSectionDao;
import sz.com.postoffice.jxyzwgcase.excellistener.PersonnelSectionListener;
import sz.com.postoffice.jxyzwgcase.pojo.PersonnelSectionInformation;
import sz.com.postoffice.jxyzwgcase.service.PersonnelSectionService;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName PersonnelSectionServiceImpl
 * @Deacription 人员及段道信息（营业部填报）逻辑处理层
 * @Author 王盟
 * @Date 2020/9/28 13:35
 * @Version 1.0
 **/
@Service
@Slf4j
public class PersonnelSectionServiceImpl extends BaseServiceImpl<PersonnelSectionInformation> implements PersonnelSectionService {

    @Resource
    private PersonnelSectionDao personnelSectionDao;
    @Override
    protected BaseDao<PersonnelSectionInformation> getMapper() {
        return this.personnelSectionDao;
    }

    @Override
    public String upload(MultipartFile file) {
        String name = file.getOriginalFilename().substring(0,2)+"市 ";
        PersonnelSectionListener personnelSectionListener = new PersonnelSectionListener(personnelSectionDao);
        String returnMsg="";

        try {
            EasyExcel.read(file.getInputStream(), PersonnelSectionInformation.class, personnelSectionListener).sheet("人员及段道信息（营业部填报）")
                    // 这里设置2,因为多行头
                    .headRowNumber(2).doRead();
            if(personnelSectionListener.getInsertFlag()){
                returnMsg="成功导入"+personnelSectionListener.getSuccessCount()+"条数据";
            }else{
                /*StringBuilder msg=new StringBuilder();
                failList.forEach(x->msg.append(x+"\t"+"\n"));*/
                List<String> failList = personnelSectionListener.getFailList();
               /* failList.parallelStream().map(new Function<String, Object>() {
                    @Override
                    public Object apply(String s) {
                        return name+s;
                    }
                });*/
                List<String> failCollect = failList.parallelStream().map(x -> name + x).collect(Collectors.toList());
                String msg = JSON.toJSONString(failCollect);
                log.info("校验返回信息：{}",msg);
                return msg;
            }

        } catch (IOException e) {
            e.printStackTrace();
            log.error("导入失败!原因是:",e);
        }
        return returnMsg;
    }
}
